package com.youlai.rocketmq.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.youlai.rocketmq.service.RocketmqCommonProblemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 消息丢失
 * @author zc
 * @date 2023-01-27 16:13
 */
@RocketMQMessageListener(  topic = "base_topic",consumerGroup = "defaultGroup", messageModel = MessageModel.BROADCASTING, consumeMode= ConsumeMode.CONCURRENTLY,consumeThreadNumber = 30)
@Service
@Slf4j
public class MessageLose implements RocketmqCommonProblemService, RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        //设置批量消费消息的最大次数,默认是1
        consumer.setConsumeMessageBatchMaxSize(10);
    }
    @Override
    public void commonProblem() {
        String text1 = "发送消息:" + RandomUtil.randomString(5);
        log.info(text1);
        //设置消息延时时间，默认3000
        rocketMQTemplate.getProducer().setSendMsgTimeout(5000);

        //开启发送失败后重试另外的broker，默认false
        rocketMQTemplate.getProducer().setRetryAnotherBrokerWhenNotStoreOK(true);

        //设置同步发送失败后的重试次数为5，4在底层会+1，默认3次
        rocketMQTemplate.getProducer().setRetryTimesWhenSendFailed(4);

        SendResult sendResult1 = rocketMQTemplate.syncSend("base_topic", text1);
        log.info("同步响应:"+sendResult1.getSendStatus().toString());
    }

    @Override
    public void onMessage(String message) {
      log.info("接收到消息:{}",message);
    }


}
